package com.iseastar.dianxiaosan.home.parcel;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.iseastar.BaseActivity2;
import com.iseastar.alipay.PayResult;
import com.iseastar.dianxiaosan.model.ParcelPayBean;
import com.iseastar.dianxiaosan.model.StampBean;
import com.iseastar.dianxiaosan.stamp.StampStoreActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.WXPayEntryActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import droid.frame.utils.android.Log;

/**
 * Created by joker on 2017/6/7.
 * 待取走包裹收银台，如果有18个包裹，邮票抵消15个包裹，剩下3个包裹的钱用支付宝或微信支付
 */
public class ParcelOrderPayTotalActivity extends BaseActivity2 implements View.OnClickListener {
    private final int SDK_PAY_FLAG = 1;
    private final int SDK_CHECK_FLAG = 2;
    //顺丰支付 ，分为全国(非偏远)和京津冀地区
    private View mSFLayoutView;//顺丰支付布局引用
    private ImageView mSFLogoIV;//顺丰logo图片
    private LinearLayout mSFUnNationwideLL;//京津冀整体布局
    private LinearLayout mSFUnNationwideNumPricelLL;//京津冀布局中包裹数量和价钱的布局
    private TextView mSFUnNationwideParcelNumTV;//京津冀包裹数量
    private TextView mSFUnNationwideParcelPricelTV;//京津冀包裹价钱
    private LinearLayout mSFUnNationwideOverWeightLL;//京津冀包裹超重整体布局
    private TextView mSFUnNationwideParcelOverWeightTV;//京津冀包裹超重
    private TextView mSFUnNationwideParcelOverWeightPricelTV;//京津冀包裹超重价钱
    private TextView mSFUnNationwideTotalPricelTV;//京津冀整体价格
    private LinearLayout mSFNationwideLL;//顺丰全国包裹布局
    private LinearLayout mSFNationwideParcelPricelLL;//全国包裹数量和价钱的整体布局
    private TextView mSFNationwideParcelNumTV;//全国包裹数量
    private TextView mSFNationwideParcelPricelTV;//全国包裹价钱,非超重
    private LinearLayout mSFNationwideParcelOverWeightLL;//全国包裹超重布局
    private TextView mSFNationwideOverWeightTV;//全国超重公斤
    private TextView mSFNationwideOverWeightPricelTV;//全国超重价钱
    private TextView mSFNationwideTotalPricelTV;//全国总价钱
    private TextView mSFTotalPricelTV;//顺丰包裹总共价钱
    //普通包裹
    private TextView mCommonParcelPricelTV;//普通包裹单间
    private TextView mCommonParcelNumTV;//普通包裹数量
    private TextView mCommonTotalPricelTV;//普通包裹总共价钱
    //使用邮票
    private LinearLayout mUserStampTypeLL;//可使用邮票类型的item
    private TextView mStampUnPayTV;//还需要支付的价钱
    private TextView mStampTipsTV;//邮票支付提示
    private RelativeLayout mStampUnPayRL;//邮票支付下面支付价钱的父布局
    //支付方式
    private CheckBox mAliPayCB, mWXPayCB;
    private TextView mPayTotalPricelTV;//总共需要支付

    private ParcelPayBean parcelPayBean = null;//从下完订单传过来的信息
    private int mParcelNum = 0;//包裹数量
    private int parcelCount = 0;//用于记录邮票抵消后剩下的包裹数量

    private String currentStr = "当前可用%1$d张";
    String payMoneyStr = "还需支付￥%1$s";
    String stampTipsStr = "抵扣包裹费用%1$s元共%2$d个包裹";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.parcel_ordertotal);
        super.findViewById();
        getAppTitle().setCommonTitle("收银台");
        initView();
        initData();
    }

    private void initView() {
        //顺丰支付布局
        mSFLayoutView = findViewById(R.id.sf_layout);
        mSFLogoIV = (ImageView) findViewById(R.id.sflogoIV);
        mSFUnNationwideLL = (LinearLayout) findViewById(R.id.sf_parcel_no_nationwide_LL);
        mSFUnNationwideNumPricelLL = (LinearLayout) findViewById(R.id.sf_parcel_no_nationwide_num_LL);
        mSFUnNationwideParcelNumTV = (TextView) findViewById(R.id.sf_parcel_no_nationwide_num_TV);
        mSFUnNationwideParcelPricelTV = (TextView) findViewById(R.id.sf_parcel_no_nationwide_pricel_TV);
        mSFUnNationwideOverWeightLL = (LinearLayout) findViewById(R.id.sf_parcel_no_nationwide_overweight_LL);
        mSFUnNationwideParcelOverWeightTV = (TextView) findViewById(R.id.sf_parcel_no_nationwide_overweight_TV);
        mSFUnNationwideParcelOverWeightPricelTV = (TextView) findViewById(R.id.sf_parcel_no_nationwide_overweight_pricel_TV);
        mSFUnNationwideTotalPricelTV = (TextView) findViewById(R.id.sf_parcel_no_nationwide_totalpricel_TV);
        mSFNationwideLL = (LinearLayout) findViewById(R.id.sf_parcel_nationwide_LL);
        mSFNationwideParcelPricelLL = (LinearLayout) findViewById(R.id.sf_parcel_nationwide_num_LL);
        mSFNationwideParcelNumTV = (TextView) findViewById(R.id.sf_parcel_nationwide_num_TV);
        mSFNationwideParcelPricelTV = (TextView) findViewById(R.id.sf_parcel_nationwide_pricel_TV);
        mSFNationwideParcelOverWeightLL = (LinearLayout) findViewById(R.id.sf_parcel_nationwide_overweight_LL);
        mSFNationwideOverWeightTV = (TextView) findViewById(R.id.sf_parcel_nationwide_overweight_TV);
        mSFNationwideOverWeightPricelTV = (TextView) findViewById(R.id.sf_parcel_nationwide_overweight_num_TV);
        mSFNationwideTotalPricelTV = (TextView) findViewById(R.id.sf_parcel_nationwide_totalpricel_TV);
        mSFTotalPricelTV = (TextView) findViewById(R.id.sf_total_pricel_TV);
        //普通包裹
        mCommonParcelPricelTV = (TextView) findViewById(R.id.commonparcelpricelTV);
        mCommonParcelNumTV = (TextView) findViewById(R.id.commonparcelnumTV);
        mCommonTotalPricelTV = (TextView) findViewById(R.id.commontotalpricelTV);
        //使用邮票
        findViewById(R.id.gostampstoreTV).setOnClickListener(this);
        mUserStampTypeLL = (LinearLayout) findViewById(R.id.stamptypeLL);
        mStampUnPayTV = (TextView) findViewById(R.id.stamp_unpayTV);
        mStampTipsTV = (TextView) findViewById(R.id.stamptipsTV);
        mStampUnPayRL = (RelativeLayout) findViewById(R.id.stampunpayRL);
        //支付方式
        findViewById(R.id.pay_ali_layout).setOnClickListener(this);
        mAliPayCB = (CheckBox) findViewById(R.id.pay_ali_checkBox);
        findViewById(R.id.pay_wx_layout).setOnClickListener(this);
        mWXPayCB = (CheckBox) findViewById(R.id.pay_wx_checkBox);
        mPayTotalPricelTV = (TextView) findViewById(R.id.paymoneyTV);
        mAliPayCB.setChecked(true);
        findViewById(R.id.payBT).setOnClickListener(this);
    }

    private void initData() {
        parcelPayBean = (ParcelPayBean) getIntent().getSerializableExtra("payData");
        mParcelNum = getIntent().getIntExtra("parcelnum", 0);
        parcelCount = mParcelNum;
//        totalCostPay = Double.parseDouble(parcelPayBean.getCost());
        showLoadingDialog(null);
        AppHttp.getInstance().parcelOrderShow(parcelPayBean.getOrderId(), mParcelNum);
        mCommonParcelNumTV.setText(mParcelNum + "");
        mCommonParcelPricelTV.setText("￥" + parcelPayBean.getPrice());
        mCommonTotalPricelTV.setText("￥" + parcelPayBean.getCost());
    }

    private void updateView(final ParcelPayBean payBean) {
        mUserStampTypeLL.removeAllViews();
        if (payBean.getStamps().size() > 0) {
            mStampUnPayRL.setVisibility(View.VISIBLE);
            for (int i = 0; i < payBean.getStamps().size(); i++) {
                final StampBean stampBean = payBean.getStamps().get(i);
                parcelCount = parcelCount - stampBean.getUseCount() * stampBean.getParcelCount();
                View itemView = LayoutInflater.from(getContext()).inflate(R.layout.parcel_userstamp_item, null);
                //邮票名称
                TextView stampNameTV = (TextView) itemView.findViewById(R.id.stampnameTV);
                //可用邮票数量
                TextView stampNumTV = (TextView) itemView.findViewById(R.id.stampnumTV);
                LinearLayout stampNumLL = (LinearLayout) itemView.findViewById(R.id.stampnumLL);
                //邮票个数
                final TextView stampCountTV = (TextView) itemView.findViewById(R.id.stampcountTV);
                stampNameTV.setText(stampBean.getName());
                stampNumTV.setText(String.format(currentStr, stampBean.getNumber()));
                stampCountTV.setText(stampBean.getUseCount() + "");
                //减去可用邮票数量
                itemView.findViewById(R.id.reduceIV).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        if (mAliPayCB.isChecked() || mWXPayCB.isChecked()) {
//                            return;
//                        }
                        int stampCount = Integer.parseInt(stampCountTV.getText().toString());//获取已经选择邮票的数量
                        if (stampCount <= 0) {
                            stampCount = 0;
                            stampCountTV.setText(stampCount + "");
                        } else {
                            stampCount -= 1;
                            stampCountTV.setText(stampCount + "");
                            parcelCount += stampBean.getParcelCount();
                            stampBean.setUseCount(stampCount);
                            updatePrice(payBean.getStamps());
                        }
                    }
                });
                //增加邮票数量
                itemView.findViewById(R.id.addIV).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        if (mAliPayCB.isChecked() || mWXPayCB.isChecked()) {
//                            return;
//                        }
                        int stampCount = Integer.parseInt(stampCountTV.getText().toString());//获取已经选择的邮票数量
                        int stampNum = stampBean.getNumber();
                        //选择的邮票数量不能大于包裹数量,并且选择的邮票不能大于可用邮票
                        if (stampCount < mParcelNum && stampCount < stampNum && parcelCount <= mParcelNum) {
                            if (parcelCount - stampBean.getParcelCount() < 0) {
                                return;
                            }
                            stampCount += 1;
                            parcelCount -= stampBean.getParcelCount();
                            stampCountTV.setText(stampCount + "");
                            stampBean.setUseCount(stampCount);
                            updatePrice(payBean.getStamps());
                        }
                    }
                });
                mUserStampTypeLL.addView(itemView);
            }
        } else {
            mStampUnPayRL.setVisibility(View.GONE);
        }
        mStampUnPayTV.setText(String.format(payMoneyStr, payBean.getCost()));
        String tipsPrice = formatPrice((mParcelNum - parcelCount) * Double.parseDouble(payBean.getPrice()));
        mStampTipsTV.setText(String.format(stampTipsStr, tipsPrice, mParcelNum - parcelCount));
    }

    /**
     * 计算更新支付的价钱,根据包裹的数量来和邮票进行匹配
     */
    private void updatePrice(ArrayList<StampBean> arrayList) {
        //stampType 0 活动的邮票 1普通的邮票 2拼包的邮票
        double price = Double.parseDouble(parcelPayBean.getPrice());//
        double unPayPrice = 0.00;
        int parcelcount = mParcelNum;
        for (int i = 0; i < arrayList.size(); i++) {
            StampBean bean = arrayList.get(i);
            if (bean.getUseCount() != 0) {
                //如果有使用的邮票则用包裹减去邮票抵消的包裹数量
                parcelcount = parcelcount - bean.getUseCount() * bean.getParcelCount();
            }
        }
        //用抵消后包裹的数量*包裹单价，还需要支付的价钱
        unPayPrice = parcelcount * price;
        mStampUnPayTV.setText(String.format(payMoneyStr, formatPrice(unPayPrice)));
        //已经抵消了的包裹数量和抵消的费用
        String tipsPrice = formatPrice((mParcelNum - parcelCount) * price);
        mStampTipsTV.setText(String.format(stampTipsStr, tipsPrice, mParcelNum - parcelCount));
    }

    public String formatPrice(double price) {
        if (price != Math.round(price)) {
            NumberFormat numberFormat = new DecimalFormat("0.00");
            return numberFormat.format(price);
        } else {
            return Integer.toString((int) price);
        }
    }

    @Override
    public void onClick(View v) {
        String unPayMoney = mStampUnPayTV.getText().toString().replace("还需支付￥", "");
        if (isEmpty(unPayMoney)) {
            unPayMoney = "0.00";
        }
        switch (v.getId()) {
            //前往邮票商场
            case R.id.gostampstoreTV:
                Intent intent = new Intent(this, StampStoreActivity.class);
                intent.putExtra("from", 1);
                startActivityForResult(intent, 101);
                break;
            //支付宝支付
            case R.id.pay_ali_layout:
                if (mAliPayCB.isChecked()) {
                    mAliPayCB.setChecked(false);
                    mWXPayCB.setChecked(false);
                } else {
                    if (Double.parseDouble(unPayMoney) == 0) {
                        mAliPayCB.setChecked(false);
                        mWXPayCB.setChecked(false);
                    } else {
                        mAliPayCB.setChecked(true);
                        mWXPayCB.setChecked(false);
                    }
                }
                break;
            //微信支付
            case R.id.pay_wx_layout:
                if (mWXPayCB.isChecked()) {
                    mAliPayCB.setChecked(false);
                    mWXPayCB.setChecked(false);
                } else {
                    if (Double.parseDouble(unPayMoney) == 0) {
                        mAliPayCB.setChecked(false);
                        mWXPayCB.setChecked(false);
                    } else {
                        mAliPayCB.setChecked(false);
                        mWXPayCB.setChecked(true);
                    }
                }
                break;
            //立即支付
            case R.id.payBT:
                payMoneyType(unPayMoney);
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.toPay_Show:
                cancelLoadingDialog();
                final ReqResult<ParcelPayBean> submitResult = JSON.parser(msg.obj, ParcelPayBean.class);
                if (checkLoginStatus(submitResult)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            parcelPayBean = null;
                            parcelPayBean = submitResult.getResult();
                            if (parcelPayBean != null) {
                                updateView(parcelPayBean);
                            }
                        }
                    });
                } else {
                    showToast(submitResult.getMessage());
                }
                return false;
            case MsgID.ali_pay:
                cancelLoadingDialog();
                ReqResult<?> aliResult = JSON.parser(msg.obj.toString());
                if (aliResult.getResult() == null) {
                    showToast("服务器异常");
                    return true;
                }
                if (checkLoginStatus(aliResult)){
                    alipay(aliResult.getResult().toString());
                }else {
                    showToast(aliResult.getMessage());
                }
                return true;
            case MsgID.weixin_pay:
                cancelLoadingDialog();
                ReqResult<WxPayModel> wxResult = JSON.parser(msg.obj.toString(), WxPayModel.class);
                if (wxResult == null) {
                    return true;
                }
                if (checkLoginStatus(wxResult)){
                    WxPayModel wxModel = wxResult.getResult();
                    if (wxModel == null) {
                        return true;
                    }
                    OrderPayBean pay = new OrderPayBean(wxModel);
                    // Intent intent = new Intent();
                    // intent.setClass(getContext(), WXPayServerActivity.class);
                    // intent.putExtra("pay", pay);
                    // startActivity(intent);

                    handleWxpay(pay);
                }else {
                    showToast(wxResult.getMessage());
                }
                return true;
            case MsgID.use_stampPay:
                cancelLoadingDialog();
                ReqResult<?> stampResult = JSON.parser(msg.obj.toString());
                if (stampResult == null) {
                    showToast("服务器异常");
                    return true;
                }
                if (checkLoginStatus(stampResult)) {
                    showToast(stampResult.getMessage());
                    setResult(Activity.RESULT_OK, new Intent());
                    ParcelOrderPayTotalActivity.this.finish();
                } else {
                    showToast(stampResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 支付的类型
     *
     * @param realCost 实际支付的价钱
     */
    private void payMoneyType(String realCost) {
        StringBuilder builder = new StringBuilder();
        if (parcelPayBean.getStamps() != null && parcelPayBean.getStamps().size() > 0) {
            StringBuilder stampIdBuilder = new StringBuilder();//邮票id
            StringBuilder stampUseCountBuilder = new StringBuilder();//使用邮票数量
            for (int i = 0; i < parcelPayBean.getStamps().size(); i++) {
                StampBean bean = parcelPayBean.getStamps().get(i);
                if (bean.getUseCount() != 0) {
                    stampIdBuilder.append(bean.getSoid() + ",");
                    stampUseCountBuilder.append(bean.getUseCount() + ",");
                }
            }
            if (isNotEmpty(stampIdBuilder.toString())) {
                builder.append(stampIdBuilder.deleteCharAt(stampIdBuilder.lastIndexOf(",")).toString() + ";" + stampUseCountBuilder.deleteCharAt(stampUseCountBuilder.lastIndexOf(",")).toString());
            }
        }
        if (!"0.00".equals(realCost) && Double.parseDouble(realCost) > 0) {
            //支付宝支付
            if (mAliPayCB.isChecked()) {
                showLoadingDialog(null);
                AppHttp.getInstance().aliPay(parcelPayBean.getOrderId(), realCost, builder.toString());
            } else if (mWXPayCB.isChecked()) {//微信支付
                final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
                if (wxapi.isWXAppInstalled() == false) {
                    showToast("未安装微信");
                    return;
                }
                showLoadingDialog(null);
                WXPayEntryActivity.payFrom = 0;
                AppHttp.getInstance().weiXinPay(parcelPayBean.getOrderId(), realCost, builder.toString());
            }
        } else {
            showLoadingDialog(null);
            AppHttp.getInstance().useStampPay(parcelPayBean.getOrderId(), builder.toString());
        }
    }

    /**
     * * 处理跳转到微信支付
     * * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(ParcelOrderPayTotalActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        AppHttp.getInstance().orderPayCallBack(parcelPayBean.getOrderId(), 2);
                        setResult(Activity.RESULT_OK);
                        ParcelOrderPayTotalActivity.super.finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(ParcelOrderPayTotalActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(ParcelOrderPayTotalActivity.this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(ParcelOrderPayTotalActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ParcelOrderPayTotalActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 101) {
            // 放在onResume是为了从邮票商城返回过来跟新数据
            Log.d("11111", "************");
            if (parcelPayBean != null) {
                Log.d("11111", "************" + parcelPayBean.getOrderId() + "====" + mParcelNum);
                showLoadingDialog(null);
                AppHttp.getInstance().parcelOrderShow(parcelPayBean.getOrderId(), mParcelNum);
            }
        }
    }
}
